// 排行榜页交互逻辑
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const rankingTable = document.getElementById('ranking-table').getElementsByTagName('tbody')[0];
    const backButton = document.getElementById('back-to-main');
    
    // 返回主页按钮事件
    backButton.addEventListener('click', function() {
        window.location.href = 'index.html';
    });
    
    // 获取排名数据
    fetchRankingData();
    
    // 获取排名数据函数
    function fetchRankingData() {
        $.ajax({
            url: 'php/rank.php',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                console.log('获取排名数据成功:', data);
                displayRanking(data);
            },
            error: function(xhr, status, error) {
                console.error('获取排名数据失败:', error);
            }
        });
    }
    
    // 显示排名数据
    function displayRanking(data) {
        // 清空现有数据
        rankingTable.innerHTML = '';
        
        // 按分数降序和剩余时间升序排序
        data.sort((a, b) => {
            if (b.score !== a.score) {
                return b.score - a.score;
            }
            return a.time - b.time;
        });
        
        // 填充表格
        data.forEach((item, index) => {
            const row = rankingTable.insertRow();
            row.className = index % 2 === 0 ? 'even-row' : 'odd-row';
            
            const rankCell = row.insertCell(0);
            rankCell.textContent = index + 1;
            
            const nameCell = row.insertCell(1);
            nameCell.textContent = item.nickname;
            
            const scoreCell = row.insertCell(2);
            scoreCell.textContent = item.score;
            
            const timeCell = row.insertCell(3);
            timeCell.textContent = item.time;
        });
    }
});